package com.offcn.oauth.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.bootstrap.encrypt.KeyProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.token.store.InMemoryTokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;
import org.springframework.security.rsa.crypto.KeyStoreKeyFactory;


import javax.annotation.Resource;
import javax.sql.DataSource;
import java.security.KeyPair;

@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

    @Autowired
    private DataSource dataSource;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private ClientDetailsService clientDetailsService;

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private UserDetailsService userDetailsService;

    @Bean
    public KeyProperties keyProperties(){
        return new KeyProperties();
    }

    @Resource
    public KeyProperties keyProperties;

    // 获取秘钥对
    private KeyPair keyPair(){
        org.springframework.core.io.Resource resource = keyProperties.getKeyStore().getLocation();
        String password = keyProperties.getKeyStore().getPassword();
        String alias = keyProperties.getKeyStore().getAlias();
        String secret = keyProperties.getKeyStore().getSecret();
        return new KeyStoreKeyFactory(resource,password.toCharArray()).getKeyPair(alias,secret.toCharArray());
    }

    // 创建 jwt转换器
    private JwtAccessTokenConverter jwtAccessTokenConverter(){
        JwtAccessTokenConverter tokenConverter = new JwtAccessTokenConverter();
        tokenConverter.setKeyPair(keyPair());
        return tokenConverter;
    }



    /**
     * 授权服务器端访问权限验证配置
     * @param security
     * @throws Exception
     */
    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        security.allowFormAuthenticationForClients() // 允许通过表单进行客户端身份认证
                .passwordEncoder(passwordEncoder)  // 设置加密器
                .tokenKeyAccess("permitAll()") //允许访问获取token的方法  http://localhost:10000/oauth/token
                .checkTokenAccess("permitAll()"); // 允许访问校验token的方法  localhost:10000/oauth/check_token
    }

    /**
     * 客户端账号配置
     * @param clients
     * @throws Exception
     */
    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        // 硬编码
//        clients.inMemory()
//                .withClient("dongyimai") // 客户端ID
//                .secret(passwordEncoder.encode("dongyimai")) // 客户端配套密码
//                .scopes("app","server") // 作用范围
//                /*
//                    authorization_code  授权码认证
//                    http://localhost:10000/oauth/authorize?client_id=dongyimai
//                        &response_type=code&scope=app
//                        &redirect_uri=http://localhost
//                    password 密码认证
//                    refresh_token  刷新令牌
//                    client_credentials  客户端模式
//                    implicit 隐式模式
//                 */
//                .authorizedGrantTypes("authorization_code", "password", "refresh_token", "client_credentials","implicit")
//                .redirectUris("http://localhost"); // 登录成功跳转地址
         // 从数据库加载客户端信息
         clients.jdbc(dataSource).clients(clientDetailsService);
    }

    // 关联 认证管理器 和 认证对象
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        // 普通令牌
        endpoints.tokenStore(new InMemoryTokenStore())
                .authenticationManager(authenticationManager) // 认证管理器
                .userDetailsService(userDetailsService)  // 认证对象
                .allowedTokenEndpointRequestMethods(HttpMethod.GET,HttpMethod.POST);

        // 使用jwt令牌
        endpoints.tokenStore(new JwtTokenStore(jwtAccessTokenConverter()))
                .accessTokenConverter(jwtAccessTokenConverter())
                .authenticationManager(authenticationManager) // 认证管理器
                .userDetailsService(userDetailsService)  // 认证对象
                .allowedTokenEndpointRequestMethods(HttpMethod.GET,HttpMethod.POST);

    }


}
